package com.zxy.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxy.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的令牌
        String token = request.getHeader("token");
        HashMap<String, Object> map = new HashMap<>();
        try {
            // 验证令牌
            JWTUtils.verify(token);
            // 放行请求
            return true;
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", "JWT验证失败");
        }
        // 将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("aaplication/json;charset=utf8");
        response.getWriter().println(json);
        return false;
    }
}
